package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.utils.AssertUtil;
import cn.wolfcode.luowowo.common.utils.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IRedisService redisService;

    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    /**
     *
     * @param phone
     * @return true: 手机号码已存在  false:不存在
     */
    @Override
    public Boolean checkPhone(String phone) {
        //判断手机格式是否这正确
        AssertUtil.testPhone(phone);
        int count = userInfoMapper.selectByPhone(phone);
        return count > 0;
    }

    @Override
    public void sendVerifyCode(String phone) throws LogicException {
        //判断手机格式是否这正确
        AssertUtil.testPhone(phone);
        //判断时效是否还在,我的防刷拓展OK?
        String verifyTimeKey = RedisKeysUtil.VERIFY_TIME.join(phone);
        if(redisService.getVerifyCode(verifyTimeKey) != null){
            throw new LogicException("验证码已发送,请稍后重试");
        }

        //1.生成验证码code
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //2.设计key,value,并设置进redis中缓存
        //key的设计
        String key = RedisKeysUtil.VERIFY_CODE.join(phone) ;
        redisService.setVerifyCode(key,code,RedisKeysUtil.VERIFY_CODE.getTime());

        //拓展:防刷短信
        redisService.setVerifyCode(verifyTimeKey,code,RedisKeysUtil.VERIFY_TIME.getTime());



        //3.发送手机短信
        System.err.println("您的验证码是:"+code+"请在"+ Consts.VERIFY_CODE_VAI_TIME+"分钟内使用");


    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException {
        //1.判断是否为空
        AssertUtil.hasLength(phone,"手机号不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //2.判断两次输入的密码是否一致
        AssertUtil.chekPasswordEquals(password,rpassword);
        //3.判断手机格式是否正确
        AssertUtil.testPhone(phone);
        //4.判断手机号码的唯一性
        if(checkPhone(phone)){
            throw new LogicException("该手机号已注册!");
        }
        //5.判断验证码是否正确
        String key = RedisKeysUtil.VERIFY_CODE.join(phone);
        String code = redisService.getVerifyCode(key);
        if(code == null){
            throw new LogicException("该验证码已失效");
        }
        //6.注册
        if(verifyCode.equals(code)){
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            userInfo.setPhone(phone);
            userInfo.setPassword(password);
            userInfo.setLevel(1);
            userInfo.setState(UserInfo.STATE_NORMAL);
            userInfo.setHeadImgUrl("/images/default.jpg");
            userInfoMapper.insert(userInfo);
        }
    }

    @Override
    public String userLogin(String username, String password) {
        //管它,先创建个token返回对象,应为tonken要塞到Cookie中给浏览器保存的,是在表现层处理的东西,与业务层无关!!!
        String token ="";
        //1.判断传进来的这儿两个东西有无值先
        AssertUtil.hasLength(username,"账号不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        //2.先去数据库查有无存在该账号
        UserInfo userInfo = userInfoMapper.queryByUsernameAndPassword(username,password);
        //3.不在就抛个异常再说
        if(userInfo == null){
            throw new LogicException("该用户不存在!");
        }
        //4.设计key和value保存在redis中保存,记得设计过期时间
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        token = RedisKeysUtil.LOGIN_USER.join(s);
        String value = JSON.toJSONString(userInfo);
        System.out.println(token);
        System.out.println(userInfo);
        redisService.setVerifyCode(token,value,RedisKeysUtil.LOGIN_USER.getTime());
        //好像没了...
        return token;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    @Override
    public void renewUserInfo(UserInfo user) {
        AssertUtil.hasObject(user.getId(),"请登录");
//        AssertUtil.hasLength(user.getNickname(),"名号不能为空");
//        AssertUtil.hasObject(user.getGender(),"性别不能为空");
//        AssertUtil.hasLength(user.getCity(),"城市不能为空");
//        AssertUtil.hasObject(user.getBirthday(),"生日不能为空");
//        AssertUtil.hasLength(user.getPhone(),"手机不能为空");

        userInfoMapper.updateByPrimaryKeyIfHasData(user);
    }

    @Override
    public void renewHeadImg(String filename, Long userId) {
        userInfoMapper.renewHeadImg(filename,userId);
    }

    @Override
    public void send(String phone) {
        AssertUtil.hasLength(phone,"手机不能为空");

        String uuid = UUID.randomUUID().toString().substring(0,4);
        StringBuilder sb = new StringBuilder();

        sb.append("您的验证码是").append(uuid).append("请在").append(2).append("分钟内填写验证");
        System.out.println(sb);
        // TODO: 2019/12/25  发送短信
//        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.getForObject("http://utf8.api.smschinese.cn/?Uid=sfgsadfsadf&Key=d41d8cd98f00b204e980&smsMob=13682260149&smsText="+sb.toString(),String.class);

        //存储到redis
        redisService.setVerifyCode("vo"+phone,uuid,120L);

    }

    @Override
    public boolean VerifyCode(String verifyCode, String phone) {
        String verifyCodeInRedis = redisService.getVerifyCode("vo"+phone);
        if(verifyCode.equals(verifyCodeInRedis)){
            return true;
        }
        return false;
    }

    @Override
    public double getSafetyIntegrity(UserInfo user) {
        double count =0;
        String nickname = user.getNickname();
        if (StringUtils.hasLength(nickname)){
            count++;
        }
        String phone = user.getPhone();
        if (StringUtils.hasLength(phone)){
            count++;
        }
        String email = user.getEmail();
        if (StringUtils.hasLength(email)){
            count++;
        }
        String password = user.getPassword();
        if (StringUtils.hasLength(password)){
            count++;
        }
        String city = user.getCity();
        if (StringUtils.hasLength(city)){
            count++;
        }
        if (user.getBirthday()!=null){
            String birthday = user.getBirthday().toString();
            if (StringUtils.hasLength(birthday)){
                count++;
            }
        }
        String headImgUrl = user.getHeadImgUrl();
        if (StringUtils.hasLength(headImgUrl)){
            count++;
        }
        String info = user.getInfo();
        if (StringUtils.hasLength(info)){
            count++;
        }

        double i = (count / 8) * 100;

        return i;
    }

    @Override
    public void delete(Long id) {
        userInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<UserInfo> getFollowers(Long id) {
        List<UserInfo> list = userInfoMapper.getFollowers(id);
        return list;
    }
}
